package com.usian.controller;

import com.usian.pojo.User;
import com.usian.service.UserService;
import com.usian.utils.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    public User login(@RequestBody User user ){
        User user1 = userService.login(user);
        if(user1!=null){

            //1:生成token
            Map<String,String> map =new HashMap<>();
            map.put("id",user1.getId().toString());
            String token = JWTUtils.getToken(map);
            user1.setToken(token);

            //2:token redis 存有效期  user_1,user_2
            redisTemplate.boundValueOps(token).set(user1.getId());
            redisTemplate.boundValueOps(token).expire(5, TimeUnit.MINUTES);

            int t = (int)redisTemplate.boundValueOps(token).get();
            System.out.println("========"+t);
        }
        return user1;
    }
}
